﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.Data;

namespace Mdb2RIA
{
    public class MdbTable
    {
        private DbConnection connection;

        public List<MdbField> TableFields { get; private set; }
        public string Name { get; private set; }

        public MdbTable(DbConnection connection, string tableName)
        {
            TableFields = new List<MdbField>();

            this.connection = connection;
            Name = tableName;

            GenerateTableSchema();
        }

        private void GenerateTableSchema()
        {
            DbCommand command = connection.CreateCommand();
            command.CommandText = "SELECT * FROM " + Name;
            DbDataReader reader = command.ExecuteReader(CommandBehavior.SchemaOnly | CommandBehavior.KeyInfo);

            DataTable schemaTable = reader.GetSchemaTable();

            foreach (DataRow field in schemaTable.Rows)
            {
                TableFields.Add(new MdbField(field));
            }
        }

        public string GenerateTableType()
        {
            StringBuilder tableType = new StringBuilder();

            Utilities.AppendMultipleLines(
                tableType,
                "using System;",
                "using System.Collections.Generic;",
                "using System.Linq;",
                "using System.Text;",
                "using System.ComponentModel;",
                "using System.ComponentModel.DataAnnotations;",
                ""
            );

            tableType.AppendLine("namespace " + Configuration.Instance.NamespaceName);
            tableType.AppendLine("{");
            tableType.AppendLine("public partial class " + Name);
            tableType.AppendLine("{");

            foreach (MdbField field in TableFields)
            {
                tableType.AppendLine(field.GenerateFieldData());
                tableType.AppendLine("");
            }


            tableType.AppendLine("}");
            tableType.AppendLine("}");

            return tableType.ToString();
        }
    }
}
